package com.qcs.sleep.warn;

import android.content.Intent;

import com.qcs.sleep.OnWarnListener;
import com.qcs.sleep.helper.DateFormatHelper;
import com.qcs.sleep.service.Action;

/**
 * Created by chshqiang on 13-10-17.
 * 护耳（声音输出）模式
 */
public class SoundWarnAdapter implements WarnAdapter {
    private OnWarnListener mListener;

    private boolean isMusicActive = false;
    private boolean isScreenLocked = false;

    private int maybeSleepTime = 0; // 可能的时间睡觉
    private int activeTime = 0; // 在可能的睡觉时间中，用户的活动时间

    private int listenMusicTime = 0;
    private int unListenMusicTime = 0; // 没有声音输出的时间

    @Override
    public void run() {
        addUpListenTime();
        addUpSleepTime();

        if (1200 < listenMusicTime) { // 声音输出时间超过一小时，则对调小媒体音量
            if (1200 <= maybeSleepTime) // 声音输出时间和睡觉时间同时超过一小时，则设置媒体音量为静音
                mListener.onWarn(70, OnWarnListener.FLAG_VOLUME, 0);
            else {
                mListener.onWarn(70, OnWarnListener.FLAG_VOLUME, 1);
            }
        }
    }

    private void addUpListenTime() {
        if (isMusicActive) {
            listenMusicTime++;

            if (unListenMusicTime > 0)
                unListenMusicTime = 0;

        } else {
            if (0 == listenMusicTime)
                return;

            unListenMusicTime++;

            if (180 <= unListenMusicTime) // 超过该限制，声音输出则重新计时
                listenMusicTime = 0;
        }

    }

    private void addUpSleepTime() { // 当前用户睡觉时间
        if (!isSleepTime()) {
            maybeSleepTime = 0;
            return;
        }

        if (isScreenLocked) {  // 该时间段里的最后一次黑屏，可以默认用户已经睡觉。
            maybeSleepTime++;

            if (activeTime > 0)
                activeTime--;

        } else { // 亮屏或未在睡觉时间段中
            if (0 == maybeSleepTime)
                return;

            activeTime++;

            if (300 <= activeTime) { // 在可能的睡觉时间里，用户的活动时间最长限制，超过该限制，则默认该用户没有睡觉
                maybeSleepTime = 0;
            }
        }
    }

    private boolean isSleepTime() {
        int time = DateFormatHelper.instance().format(System.currentTimeMillis());

        return (time > 2130 || time < 330); // 休息时间
    }

    @Override
    public void onReceive(String action) {
        if (Action.MUSIC_ON.equals(action)) {
            isMusicActive = true;
        } else if (Action.MUSIC_OFF.equals(action)) {
            isMusicActive = false;
        } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            isScreenLocked = true;
        } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
            isScreenLocked = false;
        }
    }

    @Override
    public void setOnWarnListener(OnWarnListener listener) {
        mListener = listener;
    }
}
